import React, { useState, useEffect } from 'react';
import { Space, Switch, Table, Button, Modal, Form, Input, DatePicker, InputNumber } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';

const { Item } = Form;

const UserTable = ({ userData, setUserData }) => {
    // 状态管理
    const [isModalVisible, setIsModalVisible] = useState(false); // 控制模态框显示/隐藏
    const [isAddMode, setIsAddMode] = useState(false); // 控制模态框为新增模式还是编辑模式
    const [selectedRecord, setSelectedRecord] = useState(null); // 选中的记录
    const [dataSource, setDataSource] = useState(userData); // 表格数据源
    const [currentPage, setCurrentPage] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(5); // 每页显示条目数
    const [searchKeyword, setSearchKeyword] = useState(''); // 搜索关键词
    const [form] = Form.useForm(); // 表单实例

    // 当模态框可见或选中记录变化时更新表单数据
    useEffect(() => {
        if (isModalVisible && selectedRecord) {
            form.setFieldsValue({
                username: selectedRecord.username,
                email: selectedRecord.email,
                addTime: moment(selectedRecord.addTime, 'YYYY-MM-DD'),
                isEnabled: selectedRecord.isEnabled,
                role: selectedRecord.role,
            });
        } else {
            form.resetFields();
        }
    }, [selectedRecord, isModalVisible, form]);

    // 处理编辑操作
    const handleEdit = (record) => {
        setSelectedRecord(record);
        setIsAddMode(false);
        setIsModalVisible(true);
    };

    // 处理删除操作
    const handleDelete = (record) => {
        const updatedData = dataSource.filter(item => item.key !== record.key);
        setDataSource(updatedData);
        setUserData(updatedData);
    };

    // 处理新增操作
    const handleAdd = () => {
        setSelectedRecord(null);
        setIsAddMode(true);
        setIsModalVisible(true);
    };

    // 处理取消操作
    const handleCancel = () => {
        setIsModalVisible(false);
        setSelectedRecord(null);
        form.resetFields();
    };

    // 表单提交处理函数
    const onFinish = (values) => {
        // 生成新记录的键值
        const newKey = selectedRecord ? selectedRecord.key : `${dataSource.length + 1}`;
        // 构建新记录对象
        const newRecord = {
            key: newKey,
            username: values.username,
            email: values.email,
            addTime: values.addTime.format('YYYY-MM-DD'),
            isEnabled: values.isEnabled,
            role: values.role,
        };

        // 判断是新增模式还是编辑模式
        if (isAddMode) {
            // 新增模式下，将新记录添加到数据源中
            const updatedData = [...dataSource, newRecord];
            setDataSource(updatedData);
            setUserData(updatedData);
        } else {
            // 编辑模式下，更新数据源中对应记录的内容
            const updatedData = dataSource.map(item =>
                item.key === newRecord.key ? newRecord : item
            );
            setDataSource(updatedData);
            setUserData(updatedData);
        }

        // 关闭模态框，并清空表单
        setIsModalVisible(false);
        setSelectedRecord(null);
        form.resetFields();
    };

    // 表格列配置
    const columns = [
        {
            title: '编号',
            dataIndex: 'key',
            key: 'key',
        },
        {
            title: '账号',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
        },
        {
            title: '添加时间',
            dataIndex: 'addTime',
            key: 'addTime',
        },
        {
            title: '是否启用',
            dataIndex: 'isEnabled',
            key: 'isEnabled',
            render: (isEnabled, record) => (
                <Switch
                    checked={isEnabled}
                    onChange={(checked) => {
                        // 切换启用状态时更新数据源中对应记录的 isEnabled 属性
                        const updatedData = dataSource.map(item =>
                            item.key === record.key ? { ...item, isEnabled: checked } : item
                        );
                        setDataSource(updatedData);
                        setUserData(updatedData);
                    }}
                />
            ),
        },
        {
            title: '操作',
            key: 'actions',
            render: (text, record) => (
                <Space size="middle">
                    <Button type="primary" onClick={() => handleEdit(record)}>编辑</Button>
                    <Button type="danger" onClick={() => handleDelete(record)}>删除</Button>
                </Space>
            ),
        },
    ];

    // 处理表格页码变化
    const handleTableChange =  (pagination) => {
        setCurrentPage(pagination.current);
        setPageSize(pagination.pageSize);
    };

    // 根据搜索关键词过滤数据
    const filteredData = dataSource.filter(item =>
        item.username.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        item.email.toLowerCase().includes(searchKeyword.toLowerCase())
    );

    return (
        <>
            <div className="addButtonContainer">
                {/* 新增按钮 */}
                <PlusOutlined className="addIcon" />
                <span className="addText">用户管理</span>
                {/* 搜索框 */}
                <Input
                    placeholder="搜索账号或邮箱"
                    prefix={<SearchOutlined />}
                    value={searchKeyword}
                    onChange={(e) => setSearchKeyword(e.target.value)}
                    style={{ width: 300, marginLeft: 20 }}
                />
                {/* 新增按钮 */}
                <Button type="primary" className="addButton" onClick={handleAdd}>
                    新增
                </Button>
            </div>
            {/* 用户表格 */}
            <Table
                columns={columns}
                dataSource={filteredData}
                pagination={{
                    current: currentPage,
                    pageSize: pageSize,
                    total: filteredData.length,
                    showSizeChanger: true,
                }}
                onChange={handleTableChange} // 处理表格页码变化
            />
            {/* 用户信息编辑模态框 */}
            <Modal
                title={isAddMode ? "新增用户" : "编辑用户"}
                visible={isModalVisible} // 模态框可见性
                onCancel={handleCancel}
                footer={null}
            >
                {/* 用户信息表单 */}
                <Form form={form} onFinish={onFinish}>
                    <Item name="username" label="账号" rules={[{ required: true, message: '请输入账号' }]}>
                        <Input />
                    </Item>
                    <Item name="email" label="邮箱" rules={[{ required: true, message: '请输入邮箱' }]}>
                        <Input />
                    </Item>
                    <Item name="addTime" label="添加时间" rules={[{ required: true, message: '请选择添加时间' }]}>
                        <DatePicker format="YYYY-MM-DD" />
                    </Item>
                    <Item name="isEnabled" label="是否启用" valuePropName="checked">
                        <Switch />
                    </Item>
                    <Item name="role" label="角色" rules={[{ required: true, message: '请输入角色编号' }]}>
                        <InputNumber min={1} />
                    </Item>
                    <Item>
                        <Button type="primary" htmlType="submit">
                            {isAddMode ? '新增' : '保存'}
                        </Button>
                    </Item>
                </Form>
            </Modal>
        </>
    );
};

export default UserTable;

